//
//  PotoSelectorViewController.swift
//  添加图片框架
//
//  Created by zhangguo on 15/10/21.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit
//可重用cell
private let GFPotoSelectorViewCell = "GFPotoSelectorViewCell"

//最大照片选择数量
private let kPhotoSelectorMaxCount = 2

class PhotoSelectorViewController: UICollectionViewController,PhotoSelectViewCellDelegate {
    
    private var current: Int = 0
    
    //照片数组
    lazy var photos: [UIImage] = [UIImage]()
    
    //构造函数
    init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = UIColor.whiteColor()

    self.collectionView!.registerClass(PhotoSelectViewCell.self, forCellWithReuseIdentifier: GFPotoSelectorViewCell)
        
//        定义布局属性
        let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout
        layout?.itemSize = CGSize(width: 80, height: 80)
        
        layout?.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //保证某位显示添加按钮
        //如果照片达到上限,只显示图片，不显示添加按钮
        return (photos.count == kPhotoSelectorMaxCount) ? photos.count : photos.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(GFPotoSelectorViewCell, forIndexPath: indexPath) as! PhotoSelectViewCell
    
        cell.backgroundColor = UIColor.blueColor()
        //设置照片
        cell.image = (indexPath.item < photos.count) ? photos[indexPath.item] : nil
        
        cell.photoDelegate = self
        return cell
    }
    
    //实现代理方法
    private func PhotoSelectViewCellRemovePhoto(cell:PhotoSelectViewCell) {
        print(__FUNCTION__)
        //找到照片的cell
        let indexpath = collectionView?.indexPathForCell(cell)
        //删除数组中对应的项目
        photos.removeAtIndex(indexpath!.item)
        //刷新数据
        collectionView?.reloadData()
    }
    
    private func PhotoSelectViewCellSelectPhoto(cell:PhotoSelectViewCell) {
       print(__FUNCTION__)
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
        
        print("无法访问照片库")
        return
        
    }
//      记录用户选中的cell的索引
        let indexPath = collectionView?.indexPathForCell(cell)
//        记录索引
        current = indexPath!.item
        print(indexPath)
        //实例化照片控制器
    let picker  = UIImagePickerController()
        //监听选中的照片
        picker.delegate = self
        
        //可以设置为750 *750 的图片，在用户设置图片的时候特别重要
        //设置允许编辑图片，会多一个窗口，让用户缩放图片
        //好处：是正方形的，2，会变小
//        picker.allowsEditing = true
        
        presentViewController(picker, animated: true, completion: nil)

    }
}
extension PhotoSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    //实现代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //判断当前照片是否和总数相等
        //相等
        
        //统一设置图片的宽度
        let img = image.secaleImage(300)
        
        if current == photos.count {
            //添加数据，刷新数据
            photos.append(img)
            
        }else {
            //不相等，就替换图片
            photos[current] = img
            
        }
        
        print(img)
        collectionView?.reloadData()

        //关闭播放器
        dismissViewControllerAnimated(true, completion: nil)
    }
}

//定义协议
private protocol PhotoSelectViewCellDelegate: NSObjectProtocol {
        
        //选择照片  以后写代理除了特殊情况，一定要把代理自己穿进去
    func PhotoSelectViewCellSelectPhoto(cell:PhotoSelectViewCell)
    
        //删除照片
    func PhotoSelectViewCellRemovePhoto(cell:PhotoSelectViewCell)
    
    }
    
//照片选择cell
private class PhotoSelectViewCell:UICollectionViewCell{
    
        //cell的图像
    var image:UIImage? {
        didSet {
            
            //判断图像是否为空
            if image == nil {
                
//                photoButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
//                
//                photoButton.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
//                
                photoButton.setImage("compose_pic_add")
                
                }else {
                
                photoButton.setImage(image, forState: UIControlState.Normal)
            }
                //设置删除按钮的隐藏
                removeButton.hidden = (image == nil)
        }
    }
        //定义代理
        weak var photoDelegate: PhotoSelectViewCellDelegate?
    
    //按钮监听方法
    //选择照片监听方法
      @objc  private func clickPhoto() {
            photoDelegate?.PhotoSelectViewCellSelectPhoto(self)
        }
    //删除照片监听方法
      @objc  private func clickRemove() {
            photoDelegate?.PhotoSelectViewCellRemovePhoto(self)
        }
        
        //frame
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupUI()
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        //添加控件
       private func setupUI() {
        addSubview(photoButton)
        addSubview(removeButton)
        
        //计算frame
        photoButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        let dict = ["photo":photoButton,"remove":removeButton]
        
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[photo]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[photo]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[remove]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[remove]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        //代理点击方法
        photoButton.addTarget(self, action: "clickPhoto", forControlEvents: UIControlEvents.TouchUpInside)
        removeButton.addTarget(self, action: "clickRemove", forControlEvents: UIControlEvents.TouchUpInside)
        
        //修改照片填充模式，修改button无效，需要修改image
        photoButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        }
        
        //懒加载控件
        private lazy var photoButton: UIButton = UIButton(imageNmame: "compose_pic_add")
        private lazy var removeButton: UIButton = UIButton(imageNmame: "compose_photo_close")
    }


